package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"regexp"
	"time"

	"gorm.io/gorm"
)

type Audit struct{}

func (*Audit) GetAccountAuditList(paginate *request.AccountAuditPage, claims tools.BaseClaims) (data *utils.Page, err error) {

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("无该账号信息")
	}

	var accountAuditList []*admin.AccountAudit

	global.OC_DB.Scopes(dao.AccountAuditDao.GetAccountAuditList(account.RegionLink, global.OC_DB)).Find(&accountAuditList).Offset(-1).Limit(-1).Count(&paginate.Total)

	paginate.Data = accountAuditList

	return &paginate.Page, nil
}

func (*Audit) CreateAccountAudit(accountId int, parentAccount *admin.Account, parentRole *admin.Role, db *gorm.DB) (err error) {

	var audit = map[string]interface{}{
		"presenter":    parentAccount.RealName,
		"present_role": parentRole.RoleName,
		// "belong_name":  parentAccount.NickName,
		"region_link": parentAccount.RegionLink,
		"account_id":  accountId,
		"update_time": time.Now(),
		"create_time": time.Now(),
		"status":      1,
		"result":      0,
	}

	err = db.Model(&admin.AccountAudit{}).Create(&audit).Error

	if err != nil {

		fmt.Println(err.Error())

		return errors.New("未知错误500")
	}

	return nil
}

// 审核id 审核结果result
func (*Audit) OperaAccountAudit(id int, result int, advice string, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	var auditInfo *admin.AccountAudit

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("无该账号信息")
	}

	err = global.OC_DB.First(&auditInfo, id).Error

	if err != nil {
		return errors.New("找不到该审核记录")
	}

	if auditInfo.Status == 2 {
		return errors.New("该条记录已关闭")
	}

	match, _ := regexp.MatchString(fmt.Sprintf("(%v)", account.RegionLink), auditInfo.RegionLink)

	if !match {
		return errors.New("你无权修改该条记录")
	}

	err = global.OC_DB.Transaction(func(tx *gorm.DB) error {

		err = global.OC_DB.Model(&auditInfo).Where("id = ?", id).Updates(map[string]interface{}{
			"status": 2,
			"result": result,
			"advice": advice,
		}).Error

		// 更新审核状态

		err = global.OC_DB.Model(&admin.Account{}).Where("id = ?", auditInfo.AccountId).Update("is_audit", result).Error

		if err != nil {
			return errors.New("未知错误500")
		}

		return nil
	})

	return err
}

func (*Audit) GetSingleAccountAuditInfo(id int) (data *admin.AccountAudit, err error) {

	var auditInfo *admin.AccountAudit

	err = global.OC_DB.Where("account_id = ?", id).First(&auditInfo).Error

	if err != nil {
		return nil, errors.New("该审核记录不存在")
	}

	return auditInfo, nil
}

var AuditService = new(Audit)
